///////////////////////////////////////////////////////
// KAPlayer
///////////////////////////////////////////////////////
var KAPlayer = new Object();
KAPlayer.tabs = {
	playlist:	0,
	recommend:	1
};
KAPlayer.mode = {
	order:		1,
	random:		2,
	cycle:		3
};
KAPlayer.state = {
	stop:		1,
	pause:		2,
	play:		3,
	forward:	4,
	backward:	5,
	buffer:		6,
	wait:		7,
	over:		8,
	connect:	9,
	ready:		10
};
///////////////////////////////////////////////////////
KAPlayer.initMarquee = function() {
	var direction = 1;
	setInterval(function() {
		if ($("#info span").width() < $("#info").width()) {
			$("#info").scrollLeft(0);
		} else {
			if ($("#info").scrollLeft() <= 0) {
				direction = 1;
			} else if ($("#info").scrollLeft() >= $("#info span").width()-$("#info").width()) {
				direction = -1;
			}
			$("#info").scrollLeft($("#info").scrollLeft() + direction);
		}
	}, 100);
};
KAPlayer.initProgress = function() {
	KAPlayer.progress = new KASlider({
		range: $("#progress-range"),
		route: $("#progress-route"),
		bar: $("#progress-bar"),
		overflow: false,
		onClick: function(settings) {
	        if (KAPlayer.moveEnabled && KAPlayer.player.currentMedia) {
	            KAPlayer.player.controls.currentPosition = KAPlayer.player.currentMedia.duration*settings.progress;
	        }
		},
		onMouseDown: function(settings) {
			if (KAPlayer.moveEnabled) {
				KAPlayer.moveProgress = true;
				return true;
			}
			
			return false;
		},
		onMoveStart: function(settings) {
			return KAPlayer.moveEnabled;
		},
		onMoveEnd: function(settings) {
			if (KAPlayer.player.currentMedia) {
				$("#start").text(getCurrentTime(KAPlayer.player.currentMedia.duration*settings.progress));
			}
		},
		onMouseUp: function(settings) {
	        if (KAPlayer.moveEnabled && KAPlayer.player.currentMedia) {
	            KAPlayer.player.controls.currentPosition = KAPlayer.player.currentMedia.duration*settings.progress;
	        }
			KAPlayer.moveProgress = false;
		}
	});
	
    function getCurrentTime(second) {
    	if (isNaN(second)) {
    		return "00:00";
    	} else {
            var current = (parseInt(second/60) < 10 ? "0" : "") + parseInt(second/60);
            current += ":";
            current += (parseInt(second%60) < 10 ? "0" : "") + parseInt(second%60);
            return current;
    	}
    }
};
KAPlayer.initPlayPause = function() {
	$("#play-pause").click(function() {
		if (KAPlayer.index == -1) {
			KAPlayer.playNext();
		} else if (KAPlayer.index == KAPlayer.count) {
			KAPlayer.playPrevious();
		} else {
			if (KAPlayer.player.playState == KAPlayer.state.play) {
				$(this).attr("title", "播放");
				$(this).removeClass();
				KAPlayer.player.controls.pause();
			} else {
				$(this).attr("title", "暂停");
				$(this).removeClass();
				$(this).addClass("play-pause");
				KAPlayer.player.controls.play();
				KAPlayer.playEnabled = true;
				clearInterval(KAPlayer.listener);
				KAPlayer.listener = setInterval(KAPlayer.stateListener, 10);
			}
		}
	});
	$("#play-pause").bind("mouseenter", function() {
		if ($(this)[0].className.indexOf("play-pause") > -1) {
			$(this).addClass("pause");
		} else {
			$(this).addClass("play");
		}
	});
	$("#play-pause").bind("mouseleave", function() {
		if ($(this)[0].className.indexOf("play-pause") > -1) {
			$(this).removeClass("pause");
		} else {
			$(this).removeClass("play");
		}
	});
};
KAPlayer.initStop = function() {
	$("#stop").click(function() {
        KAPlayer.playEnabled = false;
        KAPlayer.player.controls.stop();
	});
	$("#stop").bind("mouseenter mouseleave", function() {
		$(this).toggleClass("stop");
	});
};
KAPlayer.initPreviousNext = function() {
	$("#previous").click(function() {
		KAPlayer.playPrevious();
	});
	$("#previous").bind("mouseenter mouseleave", function() {
		$(this).toggleClass("previous-next");
		$("#previous-next").toggleClass("previous");
	});
	$("#next").click(function() {
		KAPlayer.playNext();
	});
	$("#next").bind("mouseenter mouseleave", function() {
		$(this).toggleClass("previous-next");
		$("#previous-next").toggleClass("next");
	});
};
KAPlayer.initVolume = function() {
	KAPlayer.volume = new KASlider({
		range: $("#volume-range"),
		route: $("#volume-route"),
		bar: $("#volume-bar"),
		overflow: false,
		progress: 1,
		onMoveEnd: function(settings) {
			if (KAPlayer.player.settings) {
				var volume = Math.floor(settings.progress*100);
				KAPlayer.player.settings.volume = volume;
				$("#volume-bar").attr("title", volume + "%");
			}
		}
	});
	
	$("#minus").bind("mouseenter mouseleave", function() {
		$(this).toggleClass("minus");
	});
	$("#add").bind("mouseenter mouseleave", function() {
		$(this).toggleClass("add");
	});
	$("#minus").click(function() {
		adjustVolume(-1);
	});
	$("#add").click(function() {
		adjustVolume(1);
	});
	
	function adjustVolume(value) {
		var sound = KAPlayer.player.settings.volume;
		sound += value;
		if (value <= 0 && sound <= 0) {
			sound = 0;
		} else if(sound >= 100) {
			sound = 100;
		}
		KAPlayer.player.settings.volume = sound;
		$("#volume-bar").attr("title", sound + "%");
		KAPlayer.volume.moveTo(sound/100);
	}
};
KAPlayer.initPlaylist = function() {
	$(".layout .tab li").each(function() {
		$(this).click(function() {
			$(".layout .tab li").removeClass("hover");
			$(this).addClass("hover");
			$(".layout .playlist").removeClass("hover");
			$(".layout .playlist:eq(" + $(this).index() + ")").addClass("hover");
		});
	});
	loadXML(KAPlayer.baseUrl + "playlist.xml", KAPlayer.tabs.playlist);
	loadXML(KAPlayer.baseUrl + "recommend.xml", KAPlayer.tabs.recommend);
	function loadXML(file, tab) {
		var playlist = "<table style='width:100%'>";
		jQuery.ajax({
			url: file,
			async: false,
			cache: false,
			dataType: "XML",
			success: function(xml) { 
				$("music", xml).each(function(i) {
					playlist += "<tr title='" + $(this).children("music-name").text() + "'>";
					switch(tab) {
						case KAPlayer.tabs.playlist:
							playlist += "<td width='10%'><input type='checkbox' onfocus='this.blur()'/></td>";
							break;
						case KAPlayer.tabs.recommend:
							playlist += "<td width='10%' align='right'>" + (i+1) + "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
							break;
						default:break;	
					}
					playlist += "<td width='90%'>" + $(this).children("music-name").text() + "</td>";
					playlist += "<td style='display:none'>" + $(this).children("music-url").text() + "</td>";
					playlist += "</tr>";
				});
			}
		});
		playlist += "</table>";
		$(".layout .playlist:eq(" + tab + ")").append(playlist);
		KAPlayer.count = $(".layout .playlist:eq(" + tab + ") table tr").length;
		$(".layout .playlist:eq(" + tab + ") table tr").each(function(i) {
			$(this).dblclick(function() {
				KAPlayer.autoPlay(i, tab);
			});
		});
		$(".layout .playlist:eq(" + tab + ") table tr").bind("mouseenter mouseleave", function() {
			$(this).toggleClass("hover");
		});
	}
};
KAPlayer.initAction = function() {
	$("#all").focus(function() {
		$(this).blur();
	});
	$("#all").click(function() {
		$(".layout .playlist:eq(0) input").prop("checked", $(this).prop("checked"));
	});
	$("#remove").click(function() {
		if ($(".layout .playlist:eq(0) input:checked").length == 0) {
			alert("请选择您要移除的歌曲！");
		} else {
			if (window.confirm("您确定要移除这些歌曲吗？")) {
				$(".layout .playlist:eq(0) table tr").each(function(i) {
					if ($(this).find("input").prop("checked")) {
						$(this).remove();
						if (KAPlayer.index >= i) {
							KAPlayer.index--;
						}
					}
				});
				if (KAPlayer.playTab == KAPlayer.tabs.playlist) {
					KAPlayer.count = $(".layout .playlist:eq(0) table tr").length;
				}
			}
		}
	});
	$("#append").click(function() {
		$("#player .append").show();
		$("#clear").click();
		$("[name='name']").focus();
	});
	$("#close").click(function() {
		$("#player .append").hide();
	});
	$("#close").focus(function() {
		$(this).blur();
	});
	$("#confirm").click(function() {
		$("[name='name']").val($.trim($("[name='name']").val()));
		$("[name='url']").val($.trim($("[name='url']").val()));
		if ($("[name='name']").val() == "") {
			alert("请您输入歌曲名！");
			$("[name='name']").focus();
		} else if ($("[name='url']").val() == "") {
			alert("请您输入链接地址！");
			$("[name='url']").focus();
		} else {
			$("#player .append").hide();
			var music = $("<tr title='" + $("[name='name']").val() + "'>"
						+ "<td width='10%'><input type='checkbox' onfocus='this.blur()'/></td>"
						+ "<td width='90%'>" + $("[name='name']").val() + "</td>"
						+ "<td style='display:none'>" + $("[name='url']").val() + "</td>"
						+ "</tr>");
			music.bind("mouseenter mouseleave", function() {
				$(this).toggleClass("hover");
			});
			var length = $(".layout .playlist:eq(0) table tr").length;
			music.dblclick(function() {
				KAPlayer.autoPlay(length, KAPlayer.tabs.playlist);
			});
			music.appendTo($(".layout .playlist:eq(0) table"));
			if (KAPlayer.playTab == KAPlayer.tabs.playlist) {
				KAPlayer.count = length + 1;
			}
		}
	});
	$("#clear").click(function() {
		$("[name='name']").val("");
		$("[name='url']").val("http://");
		$("[name='name']").focus();
	});
};
KAPlayer.initPlayMode = function() {
	$("#order").click(function() {
		$(this).parent().children(".sort").removeClass("hover");
		$(this).addClass("hover");
		KAPlayer.playMode = KAPlayer.mode.order;
	});
	$("#random").click(function() {
		$(this).parent().children(".sort").removeClass("hover");
		$(this).addClass("hover");
		KAPlayer.playMode = KAPlayer.mode.random;
	});
	$("#cycle").click(function() {
		$(this).parent().children(".sort").removeClass("hover");
		$(this).addClass("hover");
		KAPlayer.playMode = KAPlayer.mode.cycle;
	});
};
///////////////////////////////////////////////////////
KAPlayer.playPrevious = function() {
	switch(KAPlayer.playMode) {
		case KAPlayer.mode.order://order
			if (--KAPlayer.index >= 0) {
				KAPlayer.autoPlay(KAPlayer.index);
			} else if (++KAPlayer.index < 0) {
				KAPlayer.index = -1;
			}
			break;
		case KAPlayer.mode.random://random
			var index = KAPlayer.index;
			if (KAPlayer.count > 1) {
				do {
					KAPlayer.index = Math.floor(Math.random()*KAPlayer.count);
				} while (index == KAPlayer.index);	
			}
			KAPlayer.autoPlay(KAPlayer.index);
			break;
		case KAPlayer.mode.cycle://cycle
			KAPlayer.autoPlay(KAPlayer.index);
			break;
		default:break;
	}
};
KAPlayer.playNext = function() {	
	switch(KAPlayer.playMode) {
		case KAPlayer.mode.order://order
			if (++KAPlayer.index < KAPlayer.count) {
				KAPlayer.autoPlay(KAPlayer.index);
			} else {//over
				clearInterval(KAPlayer.listener);
				KAPlayer.index = KAPlayer.count;
				$("#play-pause").attr("title", "播放");
				$("#play-pause").removeClass();
				$("#start").text("");
				$("#info span").text("");
				$("#end").text("");
				$(".layout .playlist:eq(" + KAPlayer.playTab + ") table tr").removeClass("play");
			}
			break;
		case KAPlayer.mode.random://random
			var index = KAPlayer.index;
			if (KAPlayer.count > 1) {
				do {
					KAPlayer.index = Math.floor(Math.random()*KAPlayer.count);
				} while (index == KAPlayer.index);	
			}
			KAPlayer.autoPlay(KAPlayer.index);
			break;
		case KAPlayer.mode.cycle://cycle
			KAPlayer.autoPlay(KAPlayer.index);
			break;
		default:break;
	}
};
KAPlayer.autoPlay = function(index) {
	if (arguments.length > 1) {
		KAPlayer.playTab = arguments[1];
	}
	KAPlayer.index = index;
	var playlist = $(".layout .playlist:eq(" + KAPlayer.playTab + ")");
	var info = playlist.find("table tr:eq(" + index + ")");
	KAPlayer.info = info.find("td:eq(1)").text();
	KAPlayer.player.URL = info.find("td:eq(2)").text();
	playlist.find("table tr").removeClass("play");
	info.addClass("play");
	KAPlayer.count = playlist.find("table tr").length;
	$("#stop").click();
	$("#play-pause").click();
	if (info.position().top <= 0) {
		playlist.scrollTop(playlist.scrollTop() - Math.abs(info.position().top));
	} else if (info.position().top+info.height() >= playlist.height()) {
		playlist.scrollTop(playlist.scrollTop() + info.position().top - playlist.height() + info.height());
	}
};
KAPlayer.stateListener = function() {
    KAPlayer.moveEnabled = true;
	if (KAPlayer.player.controls.currentPositionString == "") {
        $("#start").text("00:00");
        KAPlayer.progress.moveTo(0);
        KAPlayer.moveEnabled = false;
    } else if (!KAPlayer.moveProgress) {
        $("#start").text(KAPlayer.player.controls.currentPositionString);
    }
    $("#end").text(KAPlayer.player.currentMedia.durationString);
	switch(KAPlayer.player.playState) {
        case KAPlayer.state.stop://stop
            if (KAPlayer.playEnabled) {
				KAPlayer.playNext();
                break;
            }
            clearInterval(KAPlayer.listener);
            $("#play-pause").attr("title", "播放");
			$("#play-pause").removeClass();
            $("#info span").text("停止播放：" + KAPlayer.info);
            break;
        case KAPlayer.state.pause://pause
            $("#info span").text("暂停播放：" + KAPlayer.info);
            break;
        case KAPlayer.state.play://play
            if (!KAPlayer.moveProgress) {
                var progress = KAPlayer.player.controls.currentPosition/KAPlayer.player.currentMedia.duration;
                KAPlayer.progress.moveTo(progress);
            }
            $("#info span").text("正在播放：" + KAPlayer.info);
            break;
        case KAPlayer.state.forward://forward
            break;
        case KAPlayer.state.backward://backward
            break;
        case KAPlayer.state.buffer://buffer
            $("#info span").text("缓冲处理：" + KAPlayer.player.network.bufferingProgress + "%");
            break;
        case KAPlayer.state.wait://wait
            break;
        case KAPlayer.state.over://over
            break;
        case KAPlayer.state.connect://connect
            $("#info span").text("正在连接：" + KAPlayer.info);
            break;
        case KAPlayer.state.ready://ready
            $("#info span").text("准备就绪：" + KAPlayer.info);
            break;
        default: break;
    }
};
///////////////////////////////////////////////////////
KAPlayer.initPlayer = function(settings) {
	settings = jQuery.extend({
		baseUrl: "kaplayer/xml/"
	}, settings);
	KAPlayer.baseUrl = settings.baseUrl;
	KAPlayer.index = -1;
	KAPlayer.count = 0;
	KAPlayer.info = "";
	KAPlayer.player = document.getElementById("ActiveX");
	KAPlayer.progress = null;
	KAPlayer.volume = null;
	KAPlayer.listener = null;
	KAPlayer.playEnabled = false;
	KAPlayer.moveEnabled = false;
	KAPlayer.moveProgress = false;
	KAPlayer.playTab = KAPlayer.tabs.playlist;
	KAPlayer.playMode = KAPlayer.mode.order;
	KAPlayer.initMarquee();
	KAPlayer.initProgress();
	KAPlayer.initPlayPause();
	KAPlayer.initStop();
	KAPlayer.initPreviousNext();
	KAPlayer.initVolume();
	KAPlayer.initPlaylist();
	KAPlayer.initAction();
	KAPlayer.initPlayMode();
	jQuery("#player div:not(.append)").bind("selectstart", function() {
		return false;
	});
};
